package com.htfyun.factorytest.playerutils;

import android.media.AudioFormat;
import android.util.Log;

import com.htfyun.factorytest.common.FTUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.htfyun.factorytest.utils.DebugLog;

public class MyPlayRunnable implements Runnable {

    private static final String TAG = "MyPlayRunnable";

    private final byte[] data;
    private final OnPlayOverCallback callback;

    private final int mFrequency = 16000;// 采样率
    private final int mChannel;


    public interface OnPlayOverCallback {
        void onPlayOverCallback();
    }

    public MyPlayRunnable(byte[] data, OnPlayOverCallback cb) {
        this(data,  AudioFormat.CHANNEL_OUT_STEREO, cb);
    }

    public MyPlayRunnable(byte[] data, int channel, OnPlayOverCallback cb) {
        // TODO Auto-generated constructor stub
        this.data = data;
        callback = cb;

        mChannel = channel;

        writeData(RECORDER_FILE_PATH, data);
    }

    public void run() {

        Log.i(TAG, "run..");

        if (data == null || data.length == 0) {
            return;
        }

        MyAudioTrack myAudioTrack = new MyAudioTrack(mFrequency,
                mChannel,
                AudioFormat.ENCODING_PCM_16BIT);

        myAudioTrack.init();

        int playSize = myAudioTrack.getPrimePlaySize();

        Log.i(TAG, "total data size = " + data.length + ", playSize = " + playSize);

        int index = 0;
        int offset = 0;
        while (true) {
            try {
                Thread.sleep(0);

                offset = index * playSize;


                if (offset >= data.length) {
                    break;
                }

                myAudioTrack.playAudioTrack(data, offset, playSize);



            } catch (Exception e) {
                // TODO: handle exception
                break;
            }

            index++;
        }

        myAudioTrack.release();

        if (callback != null) {
            callback.onPlayOverCallback();
        }

    }

    private static final String RECORDER_FILE_PATH = FTUtils.getFTStorageDirectory() + File.separator + "play.pcm";

    private void writeData(String file, byte[] data) {


        OutputStream writer = null;

        try {

            writer = new FileOutputStream(file, true);

            writer.write(data);

            writer.flush();

        } catch (Exception e) {
            DebugLog.e("Exception = " + e.getMessage());
            e.printStackTrace();

        } finally {


            if (writer != null) {
                try {
                    writer.close();
                    writer = null;
                } catch (Exception e1) {
                    DebugLog.e("Exception = " + e1.getMessage());
                    e1.printStackTrace();
                }

            }
        }
    }
}